package org.example.mall.admin.configuration.auth.grant;

import org.example.mall.admin.configuration.auth.CustomUserDetailsService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author hzq
 * @date 2021/12/6 10:42
 */
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private final CustomUserDetailsService customUserDetailsService;

    private CustomAuthenticationProvider(CustomUserDetailsService userDetailsService) {
        this.customUserDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        CustomAuthenticationToken customAuthenticationToken = (CustomAuthenticationToken) authentication;

        // 查询用户信息
        UserDetails userDetails = customUserDetailsService.loadUser(customAuthenticationToken);

        // 已认证
        CustomAuthenticationToken authenticationToken = new CustomAuthenticationToken(userDetails);

        // 绑定参数详情
        authenticationToken.setDetails(customAuthenticationToken.getDetails());

        return authenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return CustomAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public static CustomAuthenticationProvider build(CustomUserDetailsService userDetailsService) {
        return new CustomAuthenticationProvider(userDetailsService);
    }
}
